package com.osard.screen.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 保存时未设置路径，则默认放置“手机存储-Android-data-包名-Cache-Pictures”下
 * 文件名默认为时间戳
 * <p>
 * 作者：MJSoftKing
 */
public class ScreenCaptureUtils {

    private final static String TAG = ScreenCaptureUtils.class.getSimpleName();

    private String mImageName;
    private String mImagePath;

    private View view;

    private ScreenCaptureUtils() {
    }

    public static ScreenCaptureUtils createInstance() {
        return new ScreenCaptureUtils();
    }

    /**
     * @param path 保存的路径，空路径无效，相对路径将无法得知存储位置
     */
    public ScreenCaptureUtils setImagePath(String path) {
        if (TextUtils.isEmpty(path)) {
            return this;
        }
        if (!File.separator.equals(path.substring(path.length() - 1))) {
            path = path + File.separator;
        }
        mImagePath = path;
        return this;
    }

    /**
     * @param path      保存的路径
     * @param videoName 保存文件的名字
     */
    public ScreenCaptureUtils setImagePath(String path, String videoName) {
        setImagePath(path);
        setImageName(videoName);
        return this;
    }

    /**
     * @param imageName 保存文件的名字
     */
    public ScreenCaptureUtils setImageName(String imageName) {
        mImageName = imageName;
        return this;
    }

    /**
     * 截图当前Activity
     * <p>
     * 当前 Activity 不可见时获取不到 View
     */
    public ScreenCaptureUtils setView(@NonNull Activity activity) {
        Window window = activity.getWindow();
        if (null != window) {
            setView(window.getDecorView());
        }
        return this;
    }

    /**
     * 截图当前View
     */
    public ScreenCaptureUtils setView(@NonNull View view) {
        this.view = view;
        return this;
    }

    /**
     * 获取视图的截图
     *
     * @return 返回bitmap，null：出现异常或 view=null
     */
    public Bitmap screenCapture() {
        Bitmap b = null;
        //不能为空，否则抛出异常
        if (null != view) {
            b = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            c.drawColor(Color.WHITE);
            view.draw(c);
        }
        return b;
    }

    /**
     * 将视图的截图保存到指定的文件，保存为JPG
     *
     * @param quality 压缩质量 0-100，参考{@link Bitmap.CompressFormat#JPEG}
     * @return 返回保存的全路径，null：出现异常或 view=null
     */
    public String saveBitmapToJpg(int quality) {
        return saveBitmap(Bitmap.CompressFormat.JPEG, quality);
    }

    /**
     * 将视图的截图保存到指定的文件，保存为PNG
     *
     * @return 返回保存的全路径，null：出现异常或 view=null
     */
    public String saveBitmapToPng() {
        return saveBitmap(Bitmap.CompressFormat.PNG, 0);
    }

    /**
     * 将视图的截图保存到指定的文件
     *
     * @param format  格式，参考{@link Bitmap.CompressFormat}
     * @param quality 压缩质量，参考{@link Bitmap.CompressFormat}
     * @return 返回保存的全路径，null：出现异常或 view=null
     */
    public String saveBitmap(Bitmap.CompressFormat format, int quality) {
        if (null != view) {
            try {
                //储存路径未设置时的默认位置
                if (TextUtils.isEmpty(mImagePath)) {
                    mImagePath = view.getContext().getExternalCacheDir().getPath() + File.separator + Environment.DIRECTORY_PICTURES + File.separator;
                }
                //处理路径最后一位为 File.separator
                if (mImagePath.lastIndexOf(File.separator) != (mImagePath.length() - 1)) {
                    mImagePath += File.separator;
                }
                //检查并创建文件夹
                File path = new File(mImagePath);
                if (!path.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    path.mkdirs();
                }
                //未设置文件名时使用时间戳
                if (TextUtils.isEmpty(mImageName)) {
                    mImageName = System.currentTimeMillis() + ".";
                    if (Bitmap.CompressFormat.JPEG.equals(format)) {
                        mImageName += "jpg";
                    } else if (Bitmap.CompressFormat.PNG.equals(format)) {
                        mImageName += "png";
                    } else {
                        mImageName += "webp";
                    }
                }

                //质量参数取值范围 0-100
                if (quality >= 100) {
                    quality = 100;
                } else if (quality <= 0) {
                    quality = 0;
                }

                File saveFile = new File(mImagePath, mImageName);
                if (saveFile.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    saveFile.delete();
                }
                FileOutputStream saveImgOut = new FileOutputStream(saveFile);
                Bitmap bm = screenCapture();
                //compress
                bm.compress(format, quality, saveImgOut);
                //存储完成后需要清除相关的进程
                saveImgOut.flush();
                saveImgOut.close();

                return saveFile.getAbsolutePath();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
                return null;
            }
        }
        return null;
    }
}
